--- interact_link: content/08/05/plotly8-5.ipynb kernel_name: python3 kernel_path: content/08/05 has_widgets: false title: |- Bar Charts pagenum: 18 prev_page: url: /08/04/plotly8-4.html next_page: url: /08/06/plotly8-6.html suffix: .ipynb search: bar charts id plotlybarcharts plot ly python good unit describes fixed value want compare nominal values across different categories plotlybarchartsbasic basic chart plotlybarchartscustomizing customizing comment: "***PROGRAMMATICALLY GENERATED, DO NOT EDIT. SEE ORIGINAL FILES IN /content***" ---
Bar Charts

Bar Charts

Bar Charts are good to use:

  • When one unit to describes a fixed value.
  • When you want to compare nominal values across different categories.

Basic Bar Chart

import plotly.graph_objects as go
import pandas as pd
from plotly.offline import init_notebook_mode, plot
from IPython.core.display import display, HTML
init_notebook_mode(connected=True)

#Let use the cars dataset for this
car_mpg = pd.read_table('https://raw.githubusercontent.com/plotly/datasets/master/mpg_2017.txt',sep='\t')

#Let calulate the average MPG by manufacturer
#We will need to use the pandas groupby method to get the average mpgs
car_mpg_2008 = car_mpg[car_mpg['year'] ==2008] #subset to 2008
man_avg_mpg08 = car_mpg_2008.groupby('manufacturer')['cty','hwy'].mean().reset_index()


fig = go.Figure(data=[
    go.Bar(name='City MPG', x = man_avg_mpg08['manufacturer'], y=man_avg_mpg08['cty']),
    go.Bar(name='Highway MPG', x = man_avg_mpg08['manufacturer'], y=man_avg_mpg08['hwy'])
])
# Change the bar mode
fig.update_layout(barmode='group', xaxis={'categoryorder':'total ascending'},
                  title_text='Average 2008 MPG Across Makes')

plot(fig, filename = 'figure8-5-1.html')
display(HTML('figure8-5-1.html'))

Customizing Bar Charts

car_mpg_1999 = car_mpg[car_mpg['year'] ==1999] #subset to 1999
man_avg_mpg99 = car_mpg_1999.groupby('manufacturer')['cty','hwy'].mean().reset_index()
man_avg_mpg99.columns = ['manufacturer', 'cty99','hwy99']
man_mpg_08_99 = man_avg_mpg08.merge(man_avg_mpg99, on = 'manufacturer')

man_mpg_08_99['cty_diff'] = man_mpg_08_99['cty'] - man_mpg_08_99['cty99']
man_mpg_08_99['hwy_diff'] = man_mpg_08_99['hwy'] - man_mpg_08_99['hwy99']

fig = go.Figure(data=[
    go.Bar(name='City Difference', x = man_mpg_08_99['manufacturer'], y=man_mpg_08_99['cty_diff']),
    go.Bar(name='Highway Difference', x = man_mpg_08_99['manufacturer'], y=man_mpg_08_99['hwy_diff'])
])
# Change the bar mode
fig.update_layout(barmode='group', xaxis={'categoryorder':'total ascending'},
                  title_text='Average MPG Difference Between 1999-2008 Across Makes')

plot(fig, filename = 'figure8-5-2.html')
display(HTML('figure8-5-2.html'))